import 'dart:io';

import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../network/http_config.dart';
import '../../../theme/theme_color.dart';
import '../../../utils/loading.dart';
import '../../../utils/page.dart';
import '../../../utils/provider.dart';
import '../../login/Login_pass.dart';
import '../../login/WebView.dart';
import 'MeAccountSafe.dart';
import 'black_user_list.dart';

class SettingUI extends StatefulWidget {
  const SettingUI({Key? key}) : super(key: key);

  @override
  State<SettingUI> createState() => _SettingUIWidgetState();
}

class _SettingUIWidgetState extends State<SettingUI> {
  var cacheString;
  String versionStr = '1.0.0';

  final List _listData = [
    {'title': '账户安全', 'imageUrl': 'images/ic_mySafe.png'},
    {'title': '修改登录密码', 'imageUrl': 'images/ic_modifyPass.png'},
    {'title': '支付密码管理', 'imageUrl': 'images/ic_modifyPass.png'},
    {'title': '语音/视频通话提示音', 'imageUrl': 'images/ic_myVoice.png'},
    {'title': '个性化推送', 'imageUrl': 'images/ic_myVoice.png'},
    {'title': '用户协议', 'imageUrl': 'images/ic_myEditor.png'},
    {'title': '个人保护协议', 'imageUrl': 'images/ic_myProtoc.png'},
    {'title': '检查版本', 'imageUrl': 'images/ic_clearCache.png'},
    {'title': '黑名单', 'imageUrl': 'images/scan/grsz_black_list.png'},
    {'title': '备案号：京ICP备16009034号-4A', 'imageUrl': 'images/ic_myEditor.png'},
    {
      // 'title': '清除缓存',
      // 'imageUrl': 'images/ic_clearCache.png',
    },
  ];

  @override
  void initState() {
    super.initState();
  }

  Future<String> getNewVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
        childWidget: Column(
          children: [Expanded(child: _buildContent())],
        ),
        title: "个人设置",
        bgColor: ThemeColor.sendMsgColor);
  }

  Widget _buildContent() {
    return Column(
      children: [
        _buildActionButton(
            _listData[0]['imageUrl'], _listData[0]['title'], 0, true, false),
        const SizedBox(
          height: 1,
        ),
        // Divider(thickness:1.0,indent: 1,endIndent: 2,color: ThemeColor.sendMsgColor,),
        _buildActionButton(
            _listData[1]['imageUrl'], _listData[1]['title'], 1, true, false),
        const SizedBox(
          height: 1,
        ),
        _buildActionButton(
            _listData[2]['imageUrl'], _listData[2]['title'], 2, true, false),
        const SizedBox(
          height: 5,
        ),
        _buildActionButton(
          _listData[3]['imageUrl'],
          _listData[3]['title'],
          3,
          false,
          true,
        ),
        const SizedBox(
          height: 5,
        ),
        _buildActionButton(
            _listData[4]['imageUrl'], _listData[4]['title'], 4, false, true),
        const SizedBox(
          height: 1,
        ),
        _buildActionButton(
            _listData[5]['imageUrl'], _listData[5]['title'], 5, true, false),
        const SizedBox(
          height: 1,
        ),
        _buildActionButton(
            _listData[6]['imageUrl'], _listData[6]['title'], 6, true, false),
        const SizedBox(
          height: 1,
        ),
        _buildActionButton(
            _listData[7]['imageUrl'], _listData[7]['title'], 7, true, false),
        const SizedBox(
          height: 1,
        ),
        _buildActionButton(
            _listData[8]['imageUrl'], _listData[8]['title'], 8, true, true),
        const Divider(thickness: 5.0),
        const SizedBox(
          height: 1,
        ),
        CupertinoButton(
          padding: EdgeInsets.zero,
          onPressed: () {
            //退出登录
            if (kIsWeb) {
              // ThemeSnackBar.show(context, '退出成功');
              toast('退出成功~');
              Provider.remove('token');
              Navigate.toLogin();
              exit(0);
            } else {
              // _signOut();
              _signOutPopUp();
            }
          },
          child: Container(
            height: 56,
            color: Colors.white,
            child: const Center(
              child: Text(
                '退出登录',
                style: TextStyle(color: Colors.red, fontSize: 16),
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget _buildActionButton(String icon, String title, int index,
      bool isHiddenSwitch, bool isHiddenArrow) {
    return GestureDetector(
        onTap: () {
          _onClick(index);
        },
        child: Container(
          color: Colors.white,
          height: 52,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const SizedBox(
                    width: 12,
                  ),
                  Image.asset(
                    icon,
                    width: 15,
                    height: 15,
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  Text(
                    title,
                    style: TextStyle(color: ThemeColor.textColor, fontSize: 15),
                  ),
                ],
              ),
              Row(
                children: [
                  title == '检查版本'
                      ? FutureBuilder(
                          future: getNewVersion(),
                          builder: (BuildContext context,
                              AsyncSnapshot<String> snapshot) {
                            return Text(
                              snapshot.data ?? '1.0.0',
                              style: TextStyle(
                                  fontSize: 14, color: ThemeColor.appColor),
                            );
                          })
                      : _buildActionSwitch(index, isHiddenSwitch),
                  _buildActionArrow(index, isHiddenArrow),
                ],
              ),
            ],
          ),
        ));
  }

  ///是否显示switch
  Widget _buildActionSwitch(int index, bool isHiddenSwitch) {
    if (isHiddenSwitch == true) {
      return Container();
    } else {
      return InkWell(
        child: Row(
          children: [
            Container(
                margin: const EdgeInsets.only(right: 5),
                child: CupertinoSwitch(
                    value: index == 2
                        ? CommonConfig.audioSwitchSelected
                        : CommonConfig.pushSwitchSelected,
                    activeColor: ThemeColor.appColor,
                    onChanged: (value) {
                      setState(() {
                        if (index == 2) {
                          CommonConfig.audioSwitchSelected = value;
                        } else {
                          CommonConfig.pushSwitchSelected = value;
                        }
                      });
                    })),
          ],
        ),
      );
    }
  }

  ///是否显示箭头
  Widget _buildActionArrow(int index, bool isHiddenArrow) {
    if (isHiddenArrow == true) {
      return Container();
    } else {
      return Row(
        children: [
          Icon(
            Icons.arrow_forward_ios,
            color: ThemeColor.textColorSecond,
            size: 15,
          ),
          SizedBox(
            width: 12,
          ),
        ],
      );
    }
  }

  void _signOutPopUp() {
    showCupertinoDialog(
        context: context,
        builder: (cxt) {
          return CupertinoAlertDialog(
            title: const Text(
              '确认退出当前账户吗',
              style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D)),
            ),
            actions: [
              CupertinoDialogAction(
                child: const Text(
                  '取消',
                  style: TextStyle(
                    fontSize: 16,
                    color: Color(0xFF3D3D3D),
                  ),
                ),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                child: const Text(
                  '确定',
                  style: TextStyle(
                    fontSize: 16,
                    color: Color(0xFFE84D46),
                  ),
                ),
                onPressed: () {
                  Navigator.pop(context);
                  _signOut();
                },
              )
            ],
          );
        });
  }

  //添加退出
  void _signOut() async {
    try {
      await EMClient.getInstance.logout(true);
      // ThemeSnackBar.show(context, '退出成功');
      // exit(0);
      toast('退出成功~');
      Provider.remove('token');
      if (Get.currentRoute != PageRouteNames.loginPage) {
        Get.offAllNamed(PageRouteNames.loginPage);
      }
      // Navigate.toLogin();
    } on EMError catch (e) {
      // ThemeSnackBar.show(context, '退出失败');
      toast('退出失败~');
    }
  }

  _onClick(int index) {
    switch (index) {
      case 0:
        //账户安全
        Navigator.of(context).push(
            MaterialPageRoute(builder: (builder) => const MeAccountSafeUI()));
        break;
      case 1:
        //修改密码
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (ctx) => const passLoginUI()));
        break;
      case 2:
        //支付密码管理
        Get.toNamed(PageRouteNames.paymentSetting);
        break;
      case 3:
        //语音/视频通话提示音
        // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const WalletUi()));
        break;
      case 4:
        //个性化推送
        // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const WalletUi()));
        break;
      case 5:
        //用户协议
        Navigator.push(context,
            MaterialPageRoute(builder: (BuildContext context) {
          return const Browser('用户协议', '${HttpConfig.baseUrl}serv');
        }));
        break;
      case 6:
        //个人保护协议
        Navigator.push(context,
            MaterialPageRoute(builder: (BuildContext context) {
          return const Browser('个人保护协议', '${HttpConfig.baseUrl}priva');
        }));
        break;
      case 7:
        //版本更新
        if (CommonConfig.isHiddenOpen == 1) {
          toast('已经是最新版本');
          return;
        }
        _versionOfdown(context, '发现新版本');
        break;
      case 8:
        //黑名单
        Get.to(const BlackUserListPage());
        break;
    }
  }
}

Future<void> _versionOfdown(context, String title) async {
  showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: Text(title),
          actions: <Widget>[
            CupertinoDialogAction(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text(
                '取消',
                style: TextStyle(fontSize: 16, color: Colors.black),
              ),
            ),
            CupertinoDialogAction(
              onPressed: () {
                _downAndroidApp(context);
              },
              child: Text(
                '更新',
                style: TextStyle(fontSize: 16, color: ThemeColor.appColor),
              ),
            ),
          ],
        );
      });
}

_downAndroidApp(BuildContext context) async {
  String str = '';
  if (Platform.isIOS) {
    str = CommonConfig.appStoreUrl;
  } else {
    str = 'http://6ftb7.fir.run/downpage/d4bf51363a8044a2';
  }

  await launch(str);
  // await launchUrlString(str);
  Navigator.pop(context, 1);
}
